package com.zwy.core.filter;

import cn.hutool.core.util.ObjectUtil;
import com.zwy.common.exception.ResultCode;
import com.zwy.core.service.impl.UserDetailsServiceImpl;
import com.zwy.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

//    private final JwtUtils jwtUtils;
//    private final UserDetailsServiceImpl userDetailsService;
//
//    public JwtAuthenticationFilter(JwtUtils jwtUtils, UserDetailsServiceImpl userDetailsService){
//        this.jwtUtils = jwtUtils;
//        this.userDetailsService = userDetailsService;
//    }

        @Autowired
        private  JwtUtils jwtUtils;
        @Autowired
        private  UserDetailsServiceImpl userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 跳过认证接口
        if (request.getRequestURI().startsWith("/user/auth/")) {
            filterChain.doFilter(request, response);
            return;
        }
        //从请求头中获取jwt
        String header = request.getHeader("Authorization");
        if(ObjectUtil.isEmpty(header) || !header.startsWith("Bearer")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = header.substring(7);

        try {
            //验证jwt
            Claims claims = jwtUtils.validateToken(token);
            String username = claims.getSubject();

            //获取用户信息
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            //认证信息
            UsernamePasswordAuthenticationToken authenticationToken = new
                    UsernamePasswordAuthenticationToken(userDetails,
                    null, userDetails.getAuthorities());

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        } catch (Exception e) {
            response.sendError(ResultCode.UNAUTHORIZED.getCode(),"Invalid token");
            return;
        }


    }
}
